package com.yuntsg.nnsfcp.util;

import com.aspose.words.*;
import com.yuntsg.nnsfcp.config.UploadConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Calendar;

@Component
public class AsposeParseWord {

    private static InputStream license;
    @Resource
    HttpServletRequest request;
    @Resource
    UploadConfig uploadConfig;

    public String parseWord(String path) {
        if (!getLicense()) {
            return "";
        }

        Calendar calendar = Calendar.getInstance();
        String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
        String fileName = System.currentTimeMillis() + ".docx";
        String ToPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + date + "/" + fileName);
        try {
            long old = System.currentTimeMillis();
            Document doc = new Document(path);
//            DocumentBuilder documentBuilder = new DocumentBuilder(doc);
            Table table = (Table) doc.getChild(NodeType.TABLE, 0, true); //获取表格
            RowCollection rows = table.getRows();
            for (int i = 0; i < rows.getCount(); i++) {
                CellCollection cells = rows.get(i).getCells();
                for (int s = 0; s < cells.getCount(); s++) {

                    cells.get(s).getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
                }
            }
            doc.save(ToPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ToPath;
    }


    public boolean getLicense() {
        boolean result = false;
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            String licenseXml = request.getServletContext().getRealPath("/WEB-INF/classes/license.xml");
            license = new FileInputStream(licenseXml);// 凭证文件
            License aposeLic = new License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
